package com.ledi.guns.modular.ledipay.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.annotation.Resource;

import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.ledi.guns.common.exception.AppCheckException;
import com.ledi.guns.common.persistence.dao.TaskRecordMapper;
import com.ledi.guns.common.persistence.dao.UserMapper;
import com.ledi.guns.common.persistence.dao.WorkOrderMapper;
import com.ledi.guns.common.persistence.model.TaskRecord;
import com.ledi.guns.common.persistence.model.User;
import com.ledi.guns.common.persistence.model.WorkOrderInfo;
import com.ledi.guns.common.persistence.model.vo.TaskRecordVo;
import com.ledi.guns.common.persistence.model.vo.WorkOrderInfoVo;
import com.ledi.guns.core.shiro.ShiroKit;
import com.ledi.guns.core.shiro.ShiroUser;
import com.ledi.guns.core.util.SystemConstans;
import com.ledi.guns.modular.ledipay.controller.req.workOrder.AddWorkOrder;
import com.ledi.guns.modular.ledipay.controller.req.workOrder.GetTrackWorkOrder;
import com.ledi.guns.modular.ledipay.controller.req.workOrder.HandleWorkOrder;
import com.ledi.guns.modular.ledipay.controller.req.workOrder.QueryWorkOrder;
import com.ledi.guns.modular.ledipay.controller.req.workOrder.TrackWorkOrder;

@Service
@Transactional(rollbackFor = Exception.class)
public class WorkOrderServiceImpl {

	@Resource
	private WorkOrderMapper workOrderMapper;
	@Resource
	private TaskRecordMapper taskRecordMapper;
	@Resource
	private UserMapper userMapper;

	public void addWorkOrderInfo(AddWorkOrder addWorkOrder) {

		Map<String, Object> map = new HashMap();
		map.put("creater_name", addWorkOrder.getCreaterName());
		List<WorkOrderInfo> selectByMap = workOrderMapper.selectByMap(map);
		if (selectByMap.size() != 0) {
			throw new AppCheckException("workOrder.selectWorkOrderInfoError.code",
					"workOrder.selectWorkOrderInfoError.message");
		}
		WorkOrderInfo workOrderInfo = new WorkOrderInfo();
		workOrderInfo.setCreateTime(new Date());
		workOrderInfo.setVersionNo(0);
		workOrderInfo.setStatus((byte) 0);
		BeanUtils.copyProperties(addWorkOrder, workOrderInfo);
		Integer workOrderInsert = workOrderMapper.insert(workOrderInfo);
		if (workOrderInsert < 1) {
			throw new AppCheckException("workOrder.addWorkOrderInfoError.code",
					"workOrder.addWorkOrderInfoError.message");
		}
	}

	public Page<WorkOrderInfoVo> getWorkOrderInfo(Page<WorkOrderInfoVo> page, QueryWorkOrder queryWorkOrder) {

		ShiroUser currentUser = ShiroKit.getUser();
		User user = userMapper.selectById(currentUser.getId());
		if (1 != user.getStatus()) {
			throw new AppCheckException("workOrder.delete.code",
					"workOrder.delete.message", new Object[] { "无法操作工单" });
		}

		List<WorkOrderInfoVo> searchResult = workOrderMapper.getWorkOrderInfo(page, queryWorkOrder.getSearch());
		page.setRecords(searchResult);
		return page;
	}

	public void handleWorkOrder(HandleWorkOrder handleWorkOrder) {

		ShiroUser currentUser = ShiroKit.getUser();
		User user = userMapper.selectById(currentUser.getId());
		if (1 != user.getStatus()) {
			throw new AppCheckException("workOrder.delete.code",
					"workOrder.delete.message", new Object[] { "无法处理工单" });
		}
		WorkOrderInfo workOrder = workOrderMapper.selectById(handleWorkOrder.getId());
		if (null == workOrder) {
			throw new AppCheckException("workOrder.getWorkOrderInfoError.code",
					"workOrder.getWorkOrderInfoError.message");
		}
		Byte status = workOrder.getStatus();
		if (handleWorkOrder.getType() == 3) {
			if (!status.equals(new Byte("3"))) {
				throw new AppCheckException("workOrder.checkIsCloseError.code",
						"workOrder.checkIsCloseError.message");
			}
			workOrder.setStatus((byte) 2);
		} else {
			if (status.equals(new Byte("3"))) {
				throw new AppCheckException("workOrder.handleWorkOrderError.code",
						"workOrder.handleWorkOrderError.message");
			}
			if (handleWorkOrder.getType() == 1) {
				workOrder.setStatus((byte) 2);
			} else {
				workOrder.setStatus((byte) 3);
			}
		}
		workOrder.setVersionNo(handleWorkOrder.getVersionNo());
		workOrder.setUpdateTime(new Date());
		Integer handleUpdate = workOrderMapper.updateById(workOrder);
		if (handleUpdate < 1) {
			throw new AppCheckException("workOrder.HandleWorkOrderInfoError.code",
					"workOrder.HandleWorkOrderInfoError.message");
		}

		// 添加跟踪处理记录
		String contexts = "";
		if (handleWorkOrder.getType() == 3) {
			contexts = SystemConstans.ACTIVATION_WORKORDER;
		} else {
			if (handleWorkOrder.getType() == 2) {
				contexts = SystemConstans.CLOSE_WORKORDER;
			}
		}
		List<String> roleNames = currentUser.getRoleNames();
		String roles = roleNames.stream().collect(Collectors.joining(","));
		Long userId = currentUser.getId().longValue();
		TaskRecord taskRecord = new TaskRecord();
		taskRecord.setCreatorRole(roles);
		taskRecord.setCreateTime(new Date());
		taskRecord.setCreatorId(userId);
		taskRecord.setContent(contexts);
		taskRecord.setTaskId(handleWorkOrder.getId());
		Integer taskRecordInsert = taskRecordMapper.insert(taskRecord);
		if (taskRecordInsert < 1) {
			throw new AppCheckException("workOrder.insertTaskRecordError.code",
					"workOrder.insertTaskRecordError.message");
		}
	}

	public void trackWorkOrders(TrackWorkOrder trackWorkOrder) {

		ShiroUser currentUser = ShiroKit.getUser();
		User user = userMapper.selectById(currentUser.getId());
		if (1 != user.getStatus()) {
			throw new AppCheckException("workOrder.delete.code",
					"workOrder.delete.message", new Object[] { "无法处理工单" });
		}
		WorkOrderInfo workOrder = workOrderMapper.selectById(trackWorkOrder.getTaskId());
		if (null == workOrder) {
			throw new AppCheckException("workOrder.getWorkOrderInfoError.code",
					"workOrder.getWorkOrderInfoError.message");
		}
		Byte status = workOrder.getStatus();
		if (status.equals(new Byte("3"))) {
			throw new AppCheckException("workOrder.handleWorkOrderError.code",
					"workOrder.handleWorkOrderError.message");
		}
		List<String> roleNames = currentUser.getRoleNames();
		String roles = roleNames.stream().collect(Collectors.joining(","));
		Long userId = currentUser.getId().longValue();
		TaskRecord taskRecord = new TaskRecord();
		taskRecord.setCreatorRole(roles);
		taskRecord.setCreateTime(new Date());
		taskRecord.setCreatorId(userId);
		taskRecord.setContent(trackWorkOrder.getContent());
		taskRecord.setTaskId(trackWorkOrder.getTaskId());
		Integer taskRecordInsert = taskRecordMapper.insert(taskRecord);
		if (taskRecordInsert < 1) {
			throw new AppCheckException("workOrder.insertTaskRecordError.code",
					"workOrder.insertTaskRecordError.message");
		}
		// change status
		workOrder.setStatus((byte) 2);
		workOrder.setVersionNo(trackWorkOrder.getVersionNo());
		workOrder.setUpdateTime(new Date());
		Integer handleUpdate = workOrderMapper.updateById(workOrder);
		if (handleUpdate < 1) {
			throw new AppCheckException("workOrder.HandleWorkOrderInfoError.code",
					"workOrder.HandleWorkOrderInfoError.message");
		}
	}

	public List<TaskRecordVo> getTaskRecord(GetTrackWorkOrder getTrackWorkOrder) {

		ShiroUser currentUser = ShiroKit.getUser();
		User user1 = userMapper.selectById(currentUser.getId());
		if (1 != user1.getStatus()) {
			throw new AppCheckException("workOrder.delete.code",
					"workOrder.delete.message", new Object[] { "无法处理工单" });
		}
		List<TaskRecordVo> result = new ArrayList<>();
		List<TaskRecord> taskRecordLists = taskRecordMapper.selectList(new EntityWrapper<TaskRecord>()
				.eq("task_id", getTrackWorkOrder.getId())
				.orderBy("createTime", false));
		// if (null == taskRecordLists || taskRecordLists.size() <= 0) {
		// throw new AppCheckException("workOrder.selectTaskRecordError.code",
		// "workOrder.selectTaskRecordError.message");
		// }
		taskRecordLists.forEach(taskRecordList -> {
			TaskRecordVo taskRecordVo = new TaskRecordVo();
			taskRecordVo.setContent(taskRecordList.getContent());
			taskRecordVo.setCreateTime(taskRecordList.getCreateTime());
			User user = userMapper.selectById(taskRecordList.getCreatorId());
			taskRecordVo.setCreator(user.getName());
			result.add(taskRecordVo);
		});
		return result;
	}

	public WorkOrderInfo getSchoolInfo(Long id) {

		ShiroUser currentUser = ShiroKit.getUser();
		User user = userMapper.selectById(currentUser.getId());
		if (1 != user.getStatus()) {
			throw new AppCheckException("workOrder.delete.code",
					"workOrder.delete.message", new Object[] { "无法处理工单" });
		}

		WorkOrderInfo workOrderInfo = workOrderMapper.selectById(id);
		if (workOrderInfo == null || workOrderInfo.getIsDelete().equals(1)) {
			throw new AppCheckException("workOrder.selectUserError.code",
					"workOrder.selectUserError.message");
		}
		return workOrderInfo;
	}
}
